import * as echarts from '../lib/ec-canvas/echarts';
const t = getApp()
let height1=null;
let user_id=wx.getStorageSync("user_id");
t.request('/Merchant/MerchantSide/storeNums',{date_type:1,user_id:user_id,shop_id:0},function(e){
  height1=e.result.store_num*70+10;
  console.log(height1);
})
let chart1 = null;
function initChart1(canvas, width, height, dpr) {
  chart1 = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart1);
  var option = {
    disableTouch: true,
    grid: {
      top: 15,   // 等价于 y: '16%'
      left: 15, 
      right: 15,
      bottom: 15,
      containLabel: true
    },
    dataZoom: [
      {
        type: 'inside',// 内置于坐标系中
        start: 0,
        end: 4000,
        xAxisIndex: [0]
      },

    ],
    xAxis: {
      type: 'category',
      data: []
    },
    yAxis: {
      type: 'value'
    },
    series: [{
      data: [],
      type: 'bar',
      barWidth : 15,
      itemStyle: {
        normal: {
          barBorderRadius: [8, 8, 0,0],
          color: '#5b9cd6'
        }
      },
    }]
  };
  chart1.setOption(option);
  return chart1;
}
let chart2 = null;
function initChart2(canvas, width, height, dpr) {
  chart2 = echarts.init(canvas, null, {
    width: width,
    height: height,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart2);
  var option = {
    disableTouch: true,
    grid: {
      top: 15,   // 等价于 y: '16%'
      left: 15, 
      right: 15,
      bottom: 15,
      containLabel: true
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
      axisLabel: {
        rotate: 0, // 旋转角度
        interval: 0  //设置X轴数据间隔几个显示一个，为0表示都显示
    },
      data: []
    },
    series: [{
      data: [],
      type: 'bar',
      itemStyle: {
        normal: {
            // 设置颜色渐变
            color: new echarts.graphic.LinearGradient(
              1, 0, 0, 0,
              [
                  { offset: 0, color: '#58a4f8' },
                  { offset: 1, color: '#c2e1fe' }
              ]
          ),
        }
      },
      label: {
        normal: {
          show: true,
          position: 'right',
          formatter: "{c}元"
        }
      },
    }]
  };
  chart2.setOption(option);
  return chart2;
}
let chart3 = null;
function initChart3(canvas, width, height, dpr) {
  let height2=height1/3;
  chart3 = echarts.init(canvas, null, {
    width: width,
    height: height2,
    devicePixelRatio: dpr // new
  });
  canvas.setChart(chart3);
  var option = {
    disableTouch: true,
    grid: {
      top: 15,   // 等价于 y: '16%'
      left: 15, 
      right: 15,
      bottom: 15,
      containLabel: true
    },
    xAxis: {
      type: 'value',
    },
    yAxis: {
      type: 'category',
      axisLabel: {
        rotate: 0, // 旋转角度
        interval: 0  //设置X轴数据间隔几个显示一个，为0表示都显示
    },
      data: []
    },
    series: [{
      data: [],
      type: 'bar',
      itemStyle: {
        normal: {
            // 设置颜色渐变
            color: new echarts.graphic.LinearGradient(
              1, 0, 0, 0,
              [
                  { offset: 0, color: '#58a4f8' },
                  { offset: 1, color: '#c2e1fe' }
              ]
          ),
        }
      },
      label: {
        normal: {
          show: true,
          position: 'right',
          formatter: "{c}元"
        }
      },
    }]
  };
  chart3.setOption(option);
  return chart3;
}
Page({
  data: {
    openid:'',
    iconsUrl:t.globalData.iconsUrl,
    accountIndex:0,
    showbox1:false,
    shopname:'',
    shops:false,
    select1:1,
    select2:1,
    select3:1,
    select4:1,
    class:1,
    typeIndex:0,
    shoparr: [ // value传给后台的值 ， label页面上显示的文字
          {value:'0', label:'全部门店'},
        ],
    typearr: [ // value传给后台的值 ， label页面上显示的文字
          {value:'0', label:'充值金额分析'},
          {value:'1', label:'消费金额分析'},
          {value:'2', label:'洗车数量分析'},
        ],
    loading:true,
    user_id:'',
    b_id:0,
    u_name:'',
    num1:'--',
    num2:'--',
    num3:'--',
    num4:'--',
    ec1: {
      onInit: initChart1
    },
    ec2: {
      onInit: initChart2
    },
    ec3: {
      onInit: initChart3
    },
    height:350,
    scrollHeight:0,
    service_status:0, //是否显示服务费
    serviceObj:{}, //显示服务费内容
  },
  onReady: function () {
    // 获取组件
    this.ecComponent = this.selectComponent('#mychart-dom-pie2');
  },
  onLoad(e){
    const that = this;
    that.cklogin();
    that.get_service();
    that.get_shops();
    wx.getSystemInfo({
      success: (result) =>this.setData({ isIOS: result.system.match(/iOS/) }),
    });
    // 获取openid
    wx.login({
      success(e){
        t.request('/Merchant/MerchantSide/getOpenid',{code: e.code},function(event){
            that.setData({
              openid:event.result.openid,
            })
        })
      }
    })
    //that.computeScrollViewHeight();
  
    /*
    return new Promise(function (resolve, reject) {
      Promise.all([that.cklogin(), that.get_shops()]).then(function () {
      }).then(function () {
        wx.hideLoading();
        that.get_info();
        that.get_echars1();
        that.get_echars2();
      })
    })*/
  },
  onShow(e){
    this.ab()
  },
  ab(){
    t.request('/Merchant/MerchantSide/test5',{store_id:1},function(e){
      console.log(e.result)
    })
  },
  //支付服务费
  payMoney(){
    let that =this;
    var o = {
      charge_id:that.data.serviceObj.charge_id,
      openid:that.data.openid
    }
    t.request('/Merchant/MerchantSide/payCharge',o,function(e){
      // console.log(e);
      if (e.code==200) {
        var params = e.result.params
        wx.requestPayment({
          nonceStr: params.nonceStr,
          package: params.package,
          paySign: params.paySign,
          signType: 'MD5',
          timeStamp: params.timeStamp,
          'success'(e){
            that.get_service();
            // wx.hideLoading({
            //   success: (res) => {},
            // })
            // wx.navigateBack({
            //   delta: 0,
            // })
          },
          'fail'(e){
            wx.hideLoading({
              success: (res) => {},
            })
            wx.showModal({
              title: '您取消了支付！',
              showCancel:false,
              complete:function(){
              }
            })
          },
        })
      }
    })
  },
  /*computeScrollViewHeight() {
    let that = this
      let screenHeight = wx.getSystemInfoSync().windowHeight
      that.setData({
        scrollHeight: scrollHeight
      })
  },*/
  cklogin(){
    let user_id=wx.getStorageSync('user_id');
    if(user_id){
      let user=wx.getStorageSync('user');
      this.setData({
        user_id:user_id,
        u_name: user.u_name
       })
    }else{
      wx.redirectTo({
        url: '/pages/login/login',
      })
    }
  },
  // 服务费
  get_service(){
    var that = this;
    if(wx.getStorageSync('user_id')){
      t.request('/Merchant/MerchantSide/sendCharge',{user_id:that.data.user_id,b_id:that.data.b_id},function(e){
        that.setData({
          service_status:e.result.status,
          serviceObj:e.result
        })
      })
    }
  },
  get_shops(){
    var that = this;
    if(wx.getStorageSync('user_id')){
      t.request('/Merchant/MerchantSide/storeList',{user_id:that.data.user_id,b_id:that.data.b_id},function(e){
        let list=e.result.list;
        that.setData({
          accountIndex:t.globalData.accountIndex,
        })
        if(list.length>1){//多店铺
          let gid=t.globalData.b_id;
          if(gid!=0){
            that.setData({
              b_id:gid,
            })
          }
          let shoparr=[{value:'0', label:'全部门店'},];
          for(let i=0;i<list.length;i++){
            let arr ={};
            arr['value']=list[i].store_id;
            arr['label']=list[i].title;
            shoparr.push(arr);
          }
          that.setData({
            shops:true,
            shoparr:shoparr
          })
        }else{
          that.setData({
            shopname:e.result.list[0].title,
            b_id:e.result.list[0].store_id,
          })
        }
        that.get_info();
        that.get_echars1();
        that.get_echars2();
        //that.get_echars3();
      })
    }
  },
  get_info(){
    var that = this;
      t.request('/Merchant/MerchantSide/dataInfo',{user_id:that.data.user_id,shop_id:that.data.b_id},function(e){
        if(e.result.password_status==1){
          that.loginout()
          return;
        }
        
        let list =e.result.list;
        that.setData({
          num1:list[1].data,
          num2:list[2].data,
          num3:list[3].data,
          num4:list[4].data,
        })
      })
  },
  get_echars1(){
    var that = this;
    let data1=that.data;
    console.log(data1.b_id);
      t.request('/Merchant/MerchantSide/turnovers',{class_type:data1.class,date_type:data1.select1,user_id:data1.user_id,shop_id:data1.b_id},function(e){
        setTimeout(() => {
        chart1.setOption({
          xAxis: {
            data: e.result.btm
          },
          series: [{
            data: e.result.data
          }]
        })
      }, 1000);
      })
  },
  get_echars2(){
    var that = this;
    let date_type='';
    let data1=that.data;
    if(that.data.user_id!=1){
      date_type=data1.select2;
    }else{
      date_type=data1.select4;
    }
      t.request('/Merchant/MerchantSide/rankingList',{date_type:date_type,user_id:data1.user_id,shop_id:data1.b_id,nums:5},function(e){
        console.log(that.data.chart2);
        //chart2.clear();
        if(that.data.user_id!=1){
          let height=e.result.data2.length*70;
          that.setData({
            height:height,
          })
          setTimeout(() => {
            chart2.setOption({
              yAxis: {
                data: e.result.data2
              },
              series: [{
                data: e.result.nums2
              }]
            })
            }, 1000);
        }else{
          let height=e.result.data1.length*70;
          that.setData({
            height:height,
          })
          console.log(e.result.data1);
          setTimeout(() => {
            chart3.setOption({
              yAxis: {
                data: e.result.data1
              },
              series: [{
                data: e.result.nums1
              }]
            })
            }, 1000);
        }
        
      })
  },
  get_echars3(){
    var that = this;
    let data1=that.data;
      t.request('/Merchant/MerchantSide/rankingList',{date_type:data1.select4,user_id:data1.user_id,shop_id:data1.b_id,nums:0},function(e){
        let height=e.result.data.length*70;
        that.setData({
          height:height,
        })
        console.log(chart3);
        //chart2.clear();
        setTimeout(() => {
        chart3.setOption({
          yAxis: {
            data: e.result.data
          },
          series: [{
            data: e.result.num
          }]
        })
       }, 1000);
        /*hart2.getDom().style.height = height+ "rpx";
        chart2.resize();*/
        //chart2.resize({height:height}); 
      })
  },
  onRefresh(){
    //在当前页面显示导航条加载动画
    wx.showNavigationBarLoading(); 
    //显示 loading 提示框。需主动调用 wx.hideLoading 才能关闭提示框
    this.get_shops();
  },
  onPullDownRefresh: function () {
    //调用刷新时将执行的方法
    this.onRefresh();
    setTimeout(function () {
      // 不加这个方法真机下拉会一直处于刷新状态，无法复位
      wx.stopPullDownRefresh()
    }, 1000)
  },


  navigate(e){
    let page=e.currentTarget.dataset.page
    if (page == 1) {
      wx.redirectTo({
        url: '/pages/index/index',
      })
    }else if (page == 2) {
      wx.redirectTo({
        url: '/pages/info/info',
      })
    }else if(page == 3){
      wx.redirectTo({
        url: '/pages/record/record',
      })
    }else if(page == 4){
      wx.redirectTo({
        url: '/pages/shop/shop',
      })
    }
  },
  bindAccountChange(e){
    console.log('切换改变的值', e.detail.value);
    let bid=this.data.shoparr[e.detail.value];
    console.log(bid.value);
    t.globalData.b_id=bid.value;
    t.globalData.accountIndex=e.detail.value;
    this.setData({
      b_id: bid.value,
      accountIndex:e.detail.value
    })
    this.get_shops();
  },
  bindTypeChange(e){
    console.log('切换改变的值', e.detail.value);
    let bid=this.data.typearr[e.detail.value];
    console.log(bid.value);
    let val1=Number(bid.value)+1;
    this.setData({
      class: val1,
      typeIndex:e.detail.value
    })
    this.get_shops();
  },
  
  showbox1(e){
    this.setData({
      showbox1: true
    })
    setTimeout(()=>
    {
      this.setData({
        showbox1: false
      })
    }, 2000)
  },
  loginout(e){
    this.setData({
      showbox1: false
    })
    wx.removeStorageSync("user");
    wx.removeStorageSync("user_id");
    wx.reLaunch({
      url: '/pages/login/login',
    })
  },
  dochange1(e){
    this.setData({
      select1: e.currentTarget.dataset.index
    })
    this.get_echars1();
  },
  dochange2(e){
    this.setData({
      select2: e.currentTarget.dataset.index
    })
    this.get_echars2();
  },
  dochange3(e){
    this.setData({
      select4: e.currentTarget.dataset.index
    })
    this.get_echars2();
  },
  goto(){
    wx.navigateTo({
      url: '/pages/login/login',
    })
  },
})
